package com.etc.demo.utils;

import com.etc.demo.entity.Mail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SendMailUtil {
    @Value("${spring.mail.from}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单邮件
     *
     * @param mail
     */
    public boolean send(Mail mail) {
//        String to = mail.getTo();// 目标邮箱
        String title = mail.getTitle();// 邮件标题
        String content = mail.getContent();// 邮件正文
        SimpleMailMessage message = new SimpleMailMessage();
        boolean flag = false;
        for (int i = 0; i < mail.getTo().size(); i++) {
            message.setFrom(from);
            message.setTo(mail.getTo().get(i));
            message.setSubject(title);
            message.setText(content);
            try {
                mailSender.send(message);
                log.info("邮件发送成功");
                flag = true;
            } catch (MailException e) {
                log.error("邮件发送失败, to: {}, title: {}", mail.getTo().get(i), title, e);
                flag = false;
            }
        }
        return flag;
    }
}